package com.yuanchu.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-01-21 13:37
 */
@RestController
@RequestMapping("/oauth")
public class AuthorityController {

    @Resource
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private RestTemplate restTemplate;

    // OAuth服务器URL是http://localhost:8080/oauth/token
    private static final String OAUTH_TOKEN_URL = "http://localhost:10001/auth/oauth/token";

    /*@PostMapping("/loginTwo")
    public R login(@RequestBody AuthParamsDto params) throws HttpRequestMethodNotSupportedException {
        User clientUser = new User("XcWebApp", "XcWebApp", new ArrayList<>());
        //生成已经认证的client
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(clientUser, null, new ArrayList<>());
        //封装成一个UserPassword方式的参数体
        Map<String, String> map = new HashMap<>();
        map.put("username", JSON.toJSONString(params));
        // map.put("username", params.getUsername());
        // map.put("password", params.getPassword());
        //授权模式为：密码模式
        map.put("grant_type", "password");

        //调用自带的获取token方法。
        OAuth2AccessToken resultToken = tokenEndpoint.postAccessToken(token, map).getBody();
        return R.ok().put("data", resultToken);
    }*/


/*
    @PostMapping("/get-token")
    public ResponseEntity<?> getToken(@RequestBody AuthParamsDto param) {
        // 准备请求头，包含基本认证信息（client_id和client_secret）
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // headers.setBasicAuth("client-id", "client-secret");
        headers.setBasicAuth("XcWebApp", "XcWebApp");

        // 准备请求体参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "password");
        params.add("username", JSON.toJSONString(param));
        params.add("password", "your_password");
        params.add("scope", "read write");

        // 发送POST请求
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);

        // 使用RestTemplate发送请求并获取响应
        ResponseEntity<Map> response = restTemplate.postForEntity(OAUTH_TOKEN_URL, entity, Map.class);

        // 处理响应结果
        if (response.getStatusCode().is2xxSuccessful()) {
            return ResponseEntity.ok(response.getBody());
        } else {
            return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
        }
    }



    @PostMapping("/pass/login")
    public R login(@RequestBody AuthParamsDto params, @RequestHeader HttpHeaders httpHeaders) throws UnsupportedEncodingException {
        // 构造 post的body内容（要post的内容，按需定义）
        MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.set("grant_type", "password");
        String username = params.getUsername();
        String jsonString = JSON.toJSONString(params);
        paramsMap.set("username", jsonString);
        String password = params.getPassword();
        paramsMap.set("client_id", "XcWebApp");
        paramsMap.set("client_secret", "XcWebApp");
        // paramsMap.set("password", password);

        // BASE64Decoder decoder = new BASE64Decoder();
        // try {
        //     paramsMap.set("password", new String(decoder.decodeBuffer(password)));
        // } catch (IOException e) {
        //     return R.error("密码有误");
        // }
        // 使用客户端的请求头,发起请求
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        // 强制移除 原来的请求头,防止token失效
        httpHeaders.remove(HttpHeaders.AUTHORIZATION);
        //构造请求实体和头
        HttpEntity<AuthParamsDto> httpEntity = new HttpEntity<>(params, httpHeaders);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(paramsMap, httpHeaders);
        JSONObject authInfo = null;
        ResponseEntity<JSONObject> response = null;
        try {
            authInfo = restTemplate.postForObject(OAUTH_TOKEN_URL, request, JSONObject.class);
            // response = restTemplate.postForEntity(accessTokenUri, httpEntity, JSONObject.class);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
                e.printStackTrace();
                byte[] bs = e.getResponseBodyAsByteArray();
                String msg = new String(bs, "utf-8");
                Map<String, String> mm = (Map<String, String>) JSON.parse(msg);
                return R.error(mm.get("error_description"));
            } else {
                return R.error("登录失败");
            }
        }
        JSONObject jsonObject = new JSONObject(authInfo);
        String jwt = jsonObject.getString("access_token");
        Map<String, String> jwtMap = new HashMap<>();
        jwtMap.put("token", jwt);
        return R.ok().put("data", jwtMap);
    }
*/


}
